<template>
  <div class="favorites-page">
    <!-- 收藏列表 -->
    <main class="favorites-list">
      <div
        v-for="(item, index) in favorites"
        :key="index"
        @click="handleViewDetail(item.id)"
        class="favorite-item"
      >
        <!-- 房源图片 -->
        <div class="house-image">
          <img
            :src="item.imageUrl"
            :alt="item.title"
            @error="handleImageError"
          />
        </div>

        <!-- 房源信息 -->
        <div class="house-info">
          <h2 class="title">{{ item.title }}</h2>
          <p class="address">{{ item.address }}</p>

          <!-- 联系人信息 -->
          <div class="contact-info">
            <p><strong>联系人:</strong> {{ item.contactName }}</p>
            <p><strong>联系电话:</strong> {{ item.contactPhone }}</p>
          </div>

          <!-- 底部操作栏 -->
          <div class="info-bottom">
            <button class="cancel-btn" @click="removeFavorite(index)">
              <span class="close-icon">×</span>取消收藏
            </button>
            <div class="price">￥{{ item.monthRent }}/月</div>
          </div>
        </div>
      </div>
    </main>

    <div class="pagination">
      <button
        class="page-btn"
        :disabled="currentPage === 1"
        @click="
          currentPage--;
          console.log('Current Page:', currentPage); // 打印当前页码
          fetchFavorites();
        "
      >
        ＜
      </button>
      <span class="current-page">{{ currentPage }}</span>
      <button
        class="page-btn"
        :disabled="currentPage >= totalPages"
        @click="
          currentPage++;
          console.log('Current Page:', currentPage); // 打印当前页码
          fetchFavorites();
        "
      >
        ＞
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import api from "@/api";
import { useUserStore } from "@/stores/user";
import { ElMessage, ElMessageBox } from "element-plus";
import defaultImage from "@/assets/default-image.png";
import { useRouter } from "vue-router";

const router = useRouter();

const userStore = useUserStore();
const favorites = ref([]);
const currentPage = ref(1);
const totalPages = ref(1);
const pageSize = 3;

const handleViewDetail = (houseId) => {
  router.push({
    path: `/houses/${houseId}`,
  });
};

// 获取收藏列表
const fetchFavorites = async () => {
  try {
    const res = await api.collect.getCollectList(userStore.userInfo.id, {
      page: currentPage.value,
      size: pageSize,
    });
    console.log("API Response:", res.data);
    const API_BASE = "http://localhost:8080";

    favorites.value = res.data.data.map((item) => {
      // 处理图片逻辑
      let imageUrl = defaultImage;

      if (item.houseImageList?.length > 0) {
        const firstImage = item.houseImageList[0];
        // 移除路径开头的斜杠并拼接基础URL
        const cleanPath = firstImage.replace(/^\//, "");
        imageUrl = `${API_BASE}/${cleanPath}`;
      }

      return {
        ...item,
        imageUrl,
        originalImages: item.houseImageList || [],
      };
    });

    totalPages.value = Math.ceil(res.data.total / pageSize);
  } catch (error) {
    ElMessage.error("获取收藏列表失败");
    console.error("API Error:", error);
  }
};

const handleImageError = (event) => {
  event.target.src = defaultImage;
  event.target.style.objectFit = "contain";
  console.error("图片加载失败:", event.target.src);
};

// 取消收藏
const removeFavorite = async (index) => {
  try {
    await ElMessageBox.confirm("确定要取消收藏吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const item = favorites.value[index];
    console.log(item);

    await api.collect.collectHouse(item.id, userStore.userInfo.id);

    favorites.value.splice(index, 1);
    ElMessage.success("取消收藏成功");
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("操作失败");
    }
  }
};

// 分页处理
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
    fetchFavorites();
  }
};

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
    fetchFavorites();
  }
};

// 初始化加载
onMounted(fetchFavorites);
</script>

<style scoped>
.favorites-page {
  background: #f9f9f9;
  min-height: 100vh;
  padding-top: 60px;
}

.favorites-list {
  padding: 20px;
}

.favorite-item {
  display: flex;
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  background-color: #fff;
}

.house-image {
  width: 200px;
  height: 150px;
  flex-shrink: 0;
}

.house-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-top-left-radius: 8px;
  border-bottom-left-radius: 8px;
}

.house-image img[src*="default-image"] {
  background: #f0f2f5;
}

.house-info {
  flex: 1;
  padding: 15px;
  position: relative;
}

.title {
  font-size: 16px;
  color: #333;
  margin: 0 0 10px 0;
}

.address {
  font-size: 12px;
  color: #666;
  margin: 0 0 20px 0;
}

.contact-info p {
  margin: 5px 0;
  font-size: 12px;
  color: #666;
}

.info-bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.price {
  color: #f56c6c;
  font-size: 18px;
  font-weight: bold;
}

.cancel-btn {
  background: none;
  border: none;
  color: #999;
  cursor: pointer;
  padding: 5px;
  font-size: 13px;
}

.close-icon {
  font-size: 16px;
  margin-right: 3px;
}

.pagination {
  padding: 20px;
  text-align: center;
  background-color: #fff;
  position: sticky;
  bottom: 0;
  width: 100%;
  z-index: 1000;
}

.page-btn {
  background: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 5px 12px;
  margin: 0 5px;
  cursor: pointer;
  transition: background-color 0.2s ease-in-out;
}

.page-btn:hover {
  background-color: #e4e7ed;
}

.page-btn:disabled {
  background-color: #f5f7fa;
  color: #ccc;
  cursor: not-allowed;
}

.current-page {
  color: #1890ff;
  margin: 0 10px;
}
</style>
